package com.fagertveit.chainsawrus.graphics;

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;

import javax.microedition.khronos.opengles.GL10;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLES20;
import android.opengl.GLUtils;

import com.fagertveit.chainsawrus.io.FileIO;

public class Texture {
	String filename;
	int textureId;
	int width;
	int height;
	int minFilter;
	int magFilter;
	
	public Texture(String filename) {
		this.filename = filename;
	}
	
	public void load(FileIO fileIO) {
		int[] textureIds = new int[1];
		GLES20.glGenTextures(1, textureIds, 0);
		textureId = textureIds[0];
		
		InputStream in = null;
		try {
			in = fileIO.readAsset(filename);
			Bitmap bitmap = BitmapFactory.decodeStream(in);
			width = bitmap.getWidth();
			height = bitmap.getHeight();
			
			/* Functionality to generate texture without using GLUtil
			 * 
			byte[] buffer = new byte[bitmap.getWidth() * bitmap.getHeight() * 4];
	        
	        for ( int y = 0; y < bitmap.getHeight(); y++ )
	            for ( int x = 0; x < bitmap.getWidth(); x++ )
	            {
	                int pixel = bitmap.getPixel(x, y);
	                buffer[(y * bitmap.getWidth() + x) * 4 + 0] = (byte)((pixel >> 16) & 0xFF);
	                buffer[(y * bitmap.getWidth() + x) * 4 + 1] = (byte)((pixel >> 8) & 0xFF);
	                buffer[(y * bitmap.getWidth() + x) * 4 + 2] = (byte)((pixel >> 0) & 0xFF);
	                buffer[(y * bitmap.getWidth() + x) * 4 + 3] = (byte)((pixel >> 24) & 0xFF);
	            }
	        
	        ByteBuffer byteBuffer = ByteBuffer.allocateDirect(bitmap.getWidth() * bitmap.getHeight() * 4);
	        byteBuffer.put(buffer).position(0);
	        //GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_RGBA, width, height, 0, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, byteBuffer);
	        */
			
			GLES20.glBindTexture(GL10.GL_TEXTURE_2D, textureId);
			GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0);
			setFilters(GL10.GL_LINEAR, GL10.GL_LINEAR);
			GLES20.glBindTexture(GL10.GL_TEXTURE_2D, 0);
		} catch(IOException e) {
			throw new RuntimeException("Couldn't load texture '" + filename + "'", e);
		} finally {
			if(in != null) {
				try { in.close(); } catch (IOException e) { }
			}
		}
	}
	
	public void setFilters(int minFilter, int magFilter) {
		this.minFilter = minFilter;
		this.magFilter = magFilter;
		GLES20.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, minFilter);
		GLES20.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, magFilter);
	}
	
	public int getTextureId() {
		return textureId;
	}
	
	public float getWidth() {
		return width;
	}
	
	public float getHeight() {
		return height;
	}
	
	public void bind() {
		GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureId);
	}
}
